'''
登录与注册页面
'''
from SMS import fileManager,studentManager

user_file = 'users.json'


def show_login_page():
    page = fileManager.read_text_file('loginPage.txt')
    while 1:
        # 主页
        print(page)
        # 选择
        choice = input('请选择：')
        if choice == '1':
            print('login...')
            return login()
        elif choice == '2':
            print('register...')
            return reg()
        elif choice == '3':
            print('exit...')
            exit()
        else:
            print('输入有误')


def login():
    while 1:
        username = input('username:')
        password = input('password:')
        # 检测账号是否存在
        all_user = fileManager.read_json_file(user_file)
        if not all_user:
            print('登录失败，账号不存在')
            return
        if username not in all_user:
            print('登录失败，账号不存在')
            return
        # 检测密码是否正确
        pw = all_user[username]
        if password == pw:
            print('登录成功')
            studentManager.user_name = username
            return studentManager.show_manager_page()
        else:
            print('账号或者密码错误')
            return

"""
账号密码的存储：
程序中：用一个字典保存所有的账号和密码
数据持久化：将所有账号对应自动保存在文件中（users.json）
"""


def reg():
    while 1:
        username = input('请输入账号(3-6位)：')
        if 3 <= len(username) <= 6:
            break
        else:
            print('账号不符合规范，请重新输入')
    while 1:
        password = input('请输入密码（6-12位）：')
        if 6 <= len(password) <= 12:
            break
        else:
            print('密码不符合规范，请重新输入')
    # 检测账号是否存在
    all_user = fileManager.read_json_file(user_file)
    if not all_user:
        all_user = {}
    if username in all_user:
        print('该账号已存在')
        return reg()
    # 注册
    all_user[username] = password
    result = fileManager.write_json_file(user_file, all_user)
    if result:
        print('sign up successful')
    else:
        print('sign up failed')
